/*
 * @Descripttion:抽离出来公共方法
 * @version:
 * @Author: zhangfan
 * @email: 2207044692@qq.com
 * @Date: 2020-08-28 13:46:13
 * @LastEditors: younghxp
 * @LastEditTime: 2022-02-14 14:56:59
 */
import router from '../router'
import store from '../store'
import 'jquery'
/**
 * @description: 页面返回
 */
const goBack = function () {
  window.history.go(-1)
}

/**
 * @description: js数组实现不重复插入数据
 */
export const pushNoRepeat = function () {
  for (var i = 0; i < arguments.length; i++) {
    var ele = arguments[i]
    if (this.indexOf(ele) == -1) {
      this.push(ele)
    }
  }
}

/**
 * @description: js数组实现不重复插入数据
 */
export const remove = function (val) {
  var index = this.indexOf(val)
  if (index > -1) {
    this.splice(index, 1)
  }
}

const changeValue = function (e) {
  return e.target.value
}

/**
 * @description: 重构toFixed方法（number, 保留小数位）
 */
const toFixed = function (n, d) {
  var s = n + ''
  if (!d) d = 0
  if (s.indexOf('.') == -1) s += '.'
  s += new Array(d + 1).join('0')
  if (new RegExp('^(-|\\+)?(\\d+(\\.\\d{0,' + (d + 1) + '})?)\\d*$').test(s)) {
    var s = '0' + RegExp.$2,
      pm = RegExp.$1,
      a = RegExp.$3.length,
      b = true
    if (a == d + 2) {
      a = s.match(/\d/g)
      if (parseInt(a[a.length - 1]) > 4) {
        for (var i = a.length - 2; i >= 0; i--) {
          a[i] = parseInt(a[i]) + 1
          if (a[i] == 10) {
            a[i] = 0
            b = i != 1
          } else break
        }
      }
      s = a.join('').replace(new RegExp('(\\d+)(\\d{' + d + '})\\d$'), '$1.$2')
    }
    if (b) s = s.substr(1)
    return (pm + s).replace(/\.$/, '')
  }
  return this + ''
}

/**
 * @description: 单元格为空的情况
 */
const formatTd = function (row, column, cellValue) {
  var cellValue = $.trim(cellValue)
  if (cellValue === 0) {
    return '0'
  } else if (!cellValue || cellValue == null || cellValue == undefined) {
    return '--'
  } else {
    return cellValue
  }
}

/**
 * @description: 无权限跳转到403页面
 */
const goNoAccessPage = function () {
  router.push({
    name: '403',
    path: '/home/emptyPage/403',
  })
}

/**
 * @description: 通过子级id，获取整体数据
 */
const getFathersById = function (id, data, prop) {
  var arrRes = []
  const rev = (data, nodeId) => {
    for (var i = 0, length = data.length; i < length; i++) {
      const node = data[i]
      if (node[prop] === nodeId) {
        arrRes.unshift(node[prop])
        return true
      } else {
        if (node.children && node.children.length) {
          if (rev(node.children, nodeId)) {
            arrRes.unshift(node[prop])
            return true
          }
        }
      }
    }
    return false
  }
  rev(data, id)
  return arrRes
}

/**
 * @description: 无权限跳转到403页面
 */
const getButtonLimits = function () {
  this.axios({
    method: 'get',
    url: 'api-u/users/current',
    headers: {
      'Content-Type': 'application/json; charset=utf-8', //设置请求头请求格式为JSON
    },
  })
    .then(
      (response) => {
        store.state.buttonLimitsArr = response.data.permissions
          ? response.data.permissions
          : []
        store.state.accountType = response.data.type
        store.state.isHefeng = response.data.isHefeng
      },
      (response) => {}
    )
    .catch((error) => {})
}

/**
 * @description: 获取系统当前年月
 */
const format = function (Date) {
  var obj = {
    Y: Date.getFullYear(),
    M: Date.getMonth() + 1,
  }
  return obj.Y + '-' + supplement(obj.M)
}

function supplement(nn) {
  return (nn = nn < 10 ? '0' + nn : nn)
}

/**
 * @description: 转换数据
 */
const dataIntegration = function (replaceObj, dataArr) {
  var lastDataArr = []
  for (let i = 0; i < dataArr.length; i++) {
    var dataObj = {}
    for (const k in replaceObj) {
      dataObj[k] = dataArr[i][replaceObj[k]]
    }
    lastDataArr.push(dataObj)
  }
  return lastDataArr
}

/**
 * @description: 判断数组中是否有重复的数字
 */
const isRepeat = function (arr) {
  var hash = {}
  for (var i in arr) {
    if (hash[arr[i]]) return true
    hash[arr[i]] = true
  }
  return false
}

// 判断是否是童工，未满16岁即为童工
const isChildWorker = function (birthYear, birthMonth, birthDay) {
  var now = new Date()
  var year = now.getFullYear()
  var month = now.getMonth() + 1
  var day = now.getDate()
  var age = year - birthYear
  var count = 0
  if (age < 16) {
    count++
  }
  if (age == 16) {
    if (birthMonth > month) {
      count++
    } else if (birthMonth == month) {
      if (birthDay > day) {
        count++
      }
    }
  }
  return count
}
/**
 * @description: 指定字符串 溢出显示省略号
 */
const getSubStringSum = function (str, num) {
  let newStr
  if (str) {
    str = str + ''
    if (str.trim().length > num) {
      newStr = str.trim().substring(0, num) + '...'
    } else {
      newStr = str.trim()
    }
  } else {
    newStr = ''
  }
  return newStr
}

// 获取当前时分秒
const getCurrentTime = function () {
  let time
  let hh = new Date().getHours()
  let mf =
    new Date().getMinutes() < 10
      ? '0' + new Date().getMinutes()
      : new Date().getMinutes()
  let ss =
    new Date().getSeconds() < 10
      ? '0' + new Date().getSeconds()
      : new Date().getSeconds()
  time = hh + ':' + '00' + ':' + '00'
  return time
}
// 数字逢三一断
const formatNumber = function (value) {
  if (value === null || value === undefined) return '--'
  if (!value) return '0'
  // if (!value) return "0.00";
  var intPart = parseInt(Number(value)) //获取整数部分
  var floatPart = ''
  if ((value + '').indexOf('.') > -1) {
    floatPart = '.' + (value + '').split('.')[1]
  }
  var intPartFormat = intPart.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,') //将整数部分逢三一断
  return intPartFormat + floatPart
}

/**
 * @description: 获取有权限的操作列数据
 */
const getUserPermissionList = function (arr) {
  var permissionList = this.$store.state.buttonLimitsArr
  arr.forEach((item, index) => {
    let userPermissionList = Array.isArray(item.buttonLimits)
      ? item.buttonLimits
      : [item.buttonLimits]
    if (!userPermissionList.some((e) => permissionList.includes(e))) {
      arr.splice(index, 1)
    }
  })
  return arr
}
// 驼峰转换下划线
function toLine(name) {
  if (!name) {
    return
  }
  return name.replace(/([A-Z])/g, '_$1').toLowerCase()
}
export default {
  goBack,
  changeValue,
  toFixed,
  formatTd,
  goNoAccessPage,
  getFathersById,
  getButtonLimits,
  format,
  dataIntegration,
  isRepeat,
  isChildWorker,
  getSubStringSum,
  getCurrentTime,
  formatNumber,
  getUserPermissionList,
  toLine,
}
